<?php

namespace App\Http\Controllers\API;

use App\Model\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ProductController extends Controller
{
    /**
     * @abstract 返回所有的产品数据
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function index(Request $request){
        $arrRequestParams = $request->all();
        if(array_key_exists('title',$arrRequestParams) && $arrRequestParams['title'] != ''){
            $products = DB::table('products')->where('title', 'like', '%'.$arrRequestParams['title'].'%')->get();
        }else{
            $products = DB::table('products')->get();
        }
        return response()->json(['code' => 0, 'message' => 'success', 'data' => $products],200);
    }

    /**
     * @abstract 根据指定的id获取到产品的数据
     * @param $id
     * @return mixed
     */
    public function show($id){
        $objProduct =  Product::find($id);
        return $objProduct;
    }

    /**
     * @abstract 存储页面提交过来的产品数据
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request){
        $arrPostData = $request->all();
        $created_at = date('Y-m-d H:i:s',time());
        $status = ($arrPostData['status'] == true)?1:0;
        $objProduct = new Product();
        $objProduct->title = $arrPostData['title'];
        $objProduct->price = $arrPostData['price'];
        $objProduct->simpledes = $arrPostData['simpledes'];
        $objProduct->des = $arrPostData['des'];
        $objProduct->path = $arrPostData['path'];
        $objProduct->creator = 1;
        $objProduct->created_at = $created_at;
        $objProduct->status = $status;
        $flag = $objProduct->save();
        return response()->json($flag,201);
    }

    /**
     * @abstract 根据已经存在的id更新指定的产品数据
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update(Request $request,$id){
        $objProduct = Product::findOrFail($id);
        $objProduct->update($request->all());
        return response()->json($objProduct,201);
    }

    /**
     * @abstract 根据指定的id删除对应的产品信息
     * @param $id
     * @return mixed
     */
    public function delete($id){
        $objProduct = Product::findOrFail($id);
        $objProduct->delete();
        return response()->json(null,204);
    }
}
